//app.js
App({
  //定义全局变量
  //读取里面的值 console.log(getApp().globalData.urlPath);
  globalData: {
    // getApp().globalData.urlPath
    openid: null,
    urlPath: 'https://aqiong.top/',
    userInfo: null
  },
  onLaunch: function () {
    //登录
    var obj = this;
    wx.login({
      success: function (res) {
      //验证session_key 是否过期 code 请求获取到的key和openid
      wx.checkSession({
        success: function (res1) {
          getApp().globalData.openid = wx.getStorageSync('openid');
          console.log("登录还有效");
          console.log(getApp().globalData.openid);
          if (getApp().globalData.openid == ''){
            //没有openid 重新登录
            obj.login(res);
          }
          // wx.navigateTo({
          //   url: '/pages/login/index'
          // })
          console.log(getApp().globalData);
        },
        fail: function (res1) {
          console.log("登录已失效，重新登录");
          obj.login(res);
        }
      })
       
        // wx.getUserInfo({
        //   success: function (res) {
        //     console.log(res.userInfo)
        //   }
        // })
      }
    });


    // //调用API从本地缓存中获取数据
    var logs = wx.getStorageSync('logs') || []
      logs.unshift(Date.now())
      wx.setStorageSync('logs', logs);
    },

    // 登录 获取openid
    login: function (res) {
      //重新获取openid 和session_key
      if (res.code) {
        //发起网络请求
        console.log('获取openid方法');
        wx.request({
          url: 'https://aqiong.top/index/get-code',
          data: {
            code: res.code
          },
          header: {
            'content-type': 'application/json'
          },
          success: function (res) {
            //从数据库获取用户信息
            if (res.statusCode == 200) {
              // console.log(res);
              getApp().globalData.openid = res.data.openid;
              wx.setStorageSync('openid', res.data.openid);
            } else {
              console.log(res.errMsg);
            }
          }
        })
      } else {
        console.log('登录失败！' + res.errMsg)
      }
    }
})